package org.gd.mongodb;

import com.google.gson.Gson;
import com.mongodb.*;

import java.net.UnknownHostException;
import java.util.Date;

/*import javax.crypto.KeyGenerator;*/

public class Main {

    public static void main(String[] args) {

        long t = System.currentTimeMillis();
        Mongo mongo = null;
        try {
            /* connect to mongoDB, ip and port number */
            mongo = MongoDBFactory.getInstance().getMongo();

            /* get database from MongoDB, */
            /* if database doesn't exists, mongoDB will create it automatically */
            DB db = mongo.getDB("yourdb");

            /* Get collection from MongoDB, database named "yourDB" */
            /* if collection doesn't exists, mongoDB will create it automatically */
            DBCollection collection = db.getCollection("yourCollection");

            /* create a document to store key and value */
            BasicDBObject document = new BasicDBObject();
            document.put("id", 1001);
            document.put("msg", "hello world mongoDB in Java");
            document.put("user", new MongoTestUser(Math.round(Math.random()), "name1", "login1").toBasicDBObject());
            document.put("date", new Date());
            new Gson().toJson(document);
            /*collection.insert(document);*/

            /* search query */
            BasicDBObject searchQuery = new BasicDBObject();
            searchQuery.put("id", 1001);
            DBCursor cursor = collection.find(searchQuery);

            /* loop over the cursor and display the retrieved result */
            if(cursor.size() == 0) {
                System.out.println("lines not found");
            } else {
                while (cursor.hasNext()) {
                    DBObject object = cursor.next();
                    System.out.printf("object: %s\nmsg: %s\n",
                            object, object.get("msg"));
                }
            }

            cursor.close();

            /*BasicDBObject removeQuery = new BasicDBObject();
            removeQuery.put("id", 1001);
            removeQuery.put("id", 1002);
            collection.remove(removeQuery);*/

            System.out.println("");

        } catch (UnknownHostException | MongoException e) {
            e.printStackTrace();
        } finally {
            if(mongo != null) {
                mongo.close();
            }
            System.out.printf("-----------------------------\nDone: %s ms\n",
                    (System.currentTimeMillis() - t));
        }
    }
}
